<template>
  <div class="chat" @click="closeDelButton()">
    <!-- 机器人聊天窗口 -->
    <div class="chat-container">
      <div class="chat-list">
        <div class="chat-title">
          <span v-html="this.chatTitle" />
          <el-button
            @click="switchServisePerson"
            style="margin-left: auto;"
            icon="el-icon-headset"
          >
            转接人工
          </el-button>
        </div>
        <ul>
          <li
            :id="'infoId-' + item.infoId"
            class="chat-item"
            v-for="(item, index) in chatList"
            :key="item.infoId"
          >
            <div
              class="myself"
              v-if="item.sendUserId === nowUserId && item.msgFlag === 0"
            >
              <div>
                <p>
                  {{ item.sendUserName }} <span> {{ item.sendTime }} </span>
                </p>
                <div
                  @mouseleave="item.show = false"
                  @contextmenu.prevent="revokeBtnShowFn(item)"
                >
                  <!-- 文本信息 -->
                  <p class="msg-wrapper" v-html="item.msg"></p>
                  <!-- 是否已读 -->
                  <p class="read-or-not" v-if="!fixedFlag">
                    {{ item.unreadFlag ? "已读" : "未读" }}
                  </p>
                  <div class="withdraw-wrapper" v-if="item.show">
                    <el-button
                      link
                      type="primary"
                      @click="revokeBtn(item, index)"
                      >撤回</el-button
                    >
                  </div>
                </div>
              </div>
              <div>
                <span> {{ item.sendUserName.substr(0, 1) }} </span>
              </div>
            </div>

            <div
              class="others"
              v-if="item.sendUserId !== nowUserId && item.msgFlag === 0"
            >
              <div>
                <span> {{ item.sendUserName.substr(0, 1) }} </span>
              </div>
              <div>
                <p>
                  {{ item.sendUserName }} <span> {{ item.sendTime }} </span>
                </p>
                <!-- 文件 -->
                <div v-if="item.card" class="file-wrapper">
                  <!-- 常见问题卡片 -->
                  <el-card class="box-card">
                    <div slot="header" class="clearfix">
                      <span>猜您想问</span>
                      <el-button
                        @click="changeData(index)"
                        icon="el-icon-refresh-right"
                        style="float: right; padding: 3px 0"
                        type="text"
                        >换一换</el-button
                      >
                    </div>
                    <div v-for="(o, i) in item.msg" :key="i" class="text item">
                      <el-link @click="cardBtn(o, 1)">{{ o.problem }}</el-link>
                    </div>
                  </el-card>
                </div>
                <!-- 应用级联选择器 -->
                <div v-else-if="item.cascader">
                  <el-card class="box-card">
                    <div slot="header" class="clearfix">
                      <span>请选择您要咨询的业务类型？</span>
                    </div>
                    <div class="text item">
                      <el-cascader
                        :options="item.msg"
                        clearable
                        :props="{ emitPath: false }"
                        @change="changeCascader"
                        placeholder="试试搜索"
                        filterable
                      >
                      </el-cascader>
                    </div>
                  </el-card>
                </div>
                <!-- 文本信息 -->
                <p v-else class="msg-wrapper" v-html="item.msg"></p>
              </div>
            </div>
            <!-- 退出群聊，撤回信息提示 -->
            <div
              style="text-align: center; color: #8896b7; font-size: 14px"
              v-if="item.msgFlag === 1"
            >
              <span v-html="item.msg"></span>
            </div>
          </li>
          <li ref="lastChatItemRef" class="last-chat-item"></li>
        </ul>
      </div>
      <!-- 消息发送框 -->
      <div class="chat-send" v-if="chatTitle">
        <!-- 工具栏 -->
        <div :class="['chat-tool']">
          <div class="chat-tool-item">
            <Emoji @sendEmoji="sendEmoji" />
          </div>
        </div>
        <!-- 消息输入框 -->
        <div class="chat-input">
          <el-input
            v-model="sendMessage"
            :rows="2"
            resize="none"
            type="textarea"
            @keyup.enter.native="enterSendBtn"
            placeholder="请输入对话内容"
            maxlength="200"
          />
        </div>
        <!-- 消息发送按钮 -->
        <div class="chat-send-btn">
          <el-button type="primary" @click="sendBtn" size="medium">
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/framework/utils/auth";
import {
  chatGroupQueryApi,
  chatHistoryPageApi,
  chatHistoryListApi,
  chatHistoryDelApi,
  chatHistoryRevokeApi,
  chatGroupInfoApi,
  chatGroupEditApi,
  chatGroupDelApi,
  chatGroupMemberApi,
  chatGroupExitApi,
  chatGroupAddApi,
  getOrgTreeApi,
  getSysUserPageApi,
  chatHistoryListVisitorApi,
  chatGroupQueryVisitorApi,
} from "./chatjs";
// 客服消息
import {
  listAccessInfo,
  getAccessInfo,
  delAccessInfo,
  addAccessInfo,
  updateAccessInfo,
  getAccessInfoApi,
  revokeAccessInfoApi,
  getAccessInfoAllocationApi,
  transferToArtificalList,
} from "../../api/accessInfo/AccessInfo";
import {
  listTouristUser,
  getTouristUser,
  delTouristUser,
  addTouristUser,
  updateTouristUser,
  getTouristInfo,
} from "../../api/touristUser/TouristUser";
// 问题预设
import {
  getPage,
  getSystemInfoList,
  getProblemType,
} from "@/api/problemPreset/index";
import { parseTime } from "@/framework/utils/date";
import Emoji from "./emoji.vue";
import store from "@/store";
import { cloud } from "@/framework/utils/request";
import { getUserTree } from "../../framework/api/notice";
import { async } from "@antv/x6/lib/registry/marker/async";

export default {
  name: "chatOnlinePc",

  components: {
    Emoji,
  },
  data() {
    return {
      delUserId: "",
      choseId: "",
      nowChat: false,
      delButton: false,
      nowUserId: null,
      ws: null,
      sendMessage: "",
      lastChatItemRef: null,
      sessionActive: "",
      chatTitle: "客服",
      chatList: [],
      sessionList: {},
      userInfoInPage: null,
      groupId: null,
      moreMessageBtnShow: true,
      // 是否是群组 0不是 1是
      fixedFlag: 0,
      //群组是否已解散或退出 0未解散 1已解散
      reduceFlag: 0,
      drawerVisible: false,
      // 群组成员
      groupInfo: {},
      groupUsers: [],
      adminFlag: false,
      groupForm: {
        groupName: "",
      },
      // 上传文件携带的token
      headers: {
        Authorization: getToken(),
      },
      // 上传文件地址
      uploadUrl:
        process.env.VUE_APP_BASE_API + cloud.file + "/sysFileInfo/upload",
      // 上传的文件，是否是机密文件
      paramsData: {
        secretFlag: "N",
      },
      //------弹窗字段信息-----------------------------
      isChat: true,
      isOrg: true,
      userInfo: {},
      dialogVisible: false,
      treeData: [],
      selectedUserList: [],
      filterText: "",
      treeRef: [],
      ChatRef: "",
      newGroupId: "",
      addMemberGroupId: "",
      defaultProps: {
        children: "children",
        label: "name",
      },
      orgTree: [],
      orgTreeRef: [],
      orgFilterText: "",
      orgDefaultProps: {
        children: "children",
        label: "orgName",
      },
      orgName: "",
      userActive: "",
      userInfo: {},
      userList: [],
      totalRows: null,
      lastRequestTime: null,
      youkeId: null,
      // 是否人工通讯
      index: 0,
      cardDataList: [],
      artificialOrNot: false,
      classifyCode: "pcc00021",
      //问题预设搜索条件
      filterForm: {
        pageNo: 1,
        pageSize: 10,
        problem: "",
      },
      cardOptions: []
    };
  },
  created() {
    if (localStorage.getItem("touristUuid")) {
      this.youkeId = localStorage.getItem("touristUuid");
    } else {
      let uuid = this.getTouristUid();
      this.youkeId = uuid;
      localStorage.setItem("touristUuid",uuid);
    }
    this.webSocketInit();//初始化
    this.getTouristInfo();
    this.getTreeOptions();
  },
  methods: {
    // 获取游客信息
    getTouristInfo() {
      getTouristInfo({ touristUuid: this.youkeId }).then((res) => {
        if (res.code == "00000") {
          this.nowUserId = res.data.id;
        }
      });
    },
    baseURL() {
      return process.env.VUE_APP_TARGET;
    },
    // WebSocket链接
    webSocketInit() {
      const path = this.baseURL().split("://")[1];
      // 线上
      // const path = "172.31.86.10:21023";
      const youkeId = this.youkeId; //标识
      // var wspath="ws://localhost:9528/dev-api/business/chat/online/manager/uuid&"+getToken()+"/"+youkeId;//本地
      var wspath ="ws://ctiam.com:23443/prod-api/business/chat/online/manager/uuid&"+getToken() +"/"+youkeId; //线上
      this.ws = new WebSocket(wspath);
      // console.info("init ws=",this.ws)
      this.ws.onmessage = (e) => {
        console.log("onmessage=", e);
        this.websocketonmessage(e);
      };
      this.ws.onclose = (e) => {
        console.log("onclose=", e);
        this.websocketclose(e);
      };
      this.ws.onopen = (e) => {
        console.log("open=", e);
        this.websocketOpen(e);
      };
    },
    // 链接
    websocketonmessage(e) {
      let res = JSON.parse(e.data);
      const obj = this.sessionList[res.groupId];
      let msgData = {};
      console.log("获取信息=", res);
      switch (res.code) {
        // 消息数据 msgFlag: 0消息， 1通知
        case "msgData":
          // console.log("this.chatList1=",parseTime(new Date(res.sendTime), '{y}-{m}-{d} {h}:{i}:{s}'))
          this.chatList.push({
            delFlag: 0,
            msgFlag: 0,
            msg: res.msg,
            sendTime: this.timeStampToTime(new Date(res.sendTime)),
            sendUserName: res.sendUserName,
            sendUserId: res.sendUserId,
            show: false,
          });
          this.reduceFlag = 0;
          this.sendMessage = "";
          break;
        // 确认数据
        case "ackData":
          if (res.status !== 0) {
            this.$message({
              message: res.tip,
              type: "warning",
            });
          } else {
            if (res.groupId === this.groupId) {
              let msgData = {
                delFlag: 0,
                msgFlag: 0,
                fileSuffix: res.fileSuffix,
                fileSizeInfo: res.fileSizeInfo,
                fileId: res.fileId,
                infoId: res.infoId,
                msg: res.fileId
                  ? res.msg
                  : this.sendMessage.replace(/</g, "&lt;"),
                sendTime: parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
                sendUserName: store.state.user.name,
                sendUserId: store.state.user.userId,
                show: false,
              };
              this.chatList.push(msgData);
            }
            this.sendMessage = "";
          }
          break;

        // 已读数据
        case "readData":
          if (this.groupId) {
            this.chatList.forEach((element) => {
              element.unreadFlag = 1;
            });
          }
          break;

        // 撤回数据
        case "delData":
          this.chatList.forEach((child, index) => {
            if (child.infoId === res.infoId) {
              this.chatList[index].delFlag = 1;
              this.chatList[index].msgFlag = 1;
              this.chatList[index].msg = `${child.sendUserName}撤回了一条消息`;
            }
          });
          this.sessionList[res.groupId].lastMsg = res.tip;
          this.sessionList[res.groupId].lastTime = parseTime(
            new Date(),
            "{y}-{m}-{d} {h}:{i}:{s}"
          );
          if (this.sessionList[res.groupId].unreadData > 0) {
            this.sessionList[res.groupId].unreadData--;
          }

          break;

        // 解散群聊
        case "groupDelData":
          this.drawerVisible = false;
          this.reduceFlag = 1;
          if (obj) {
            obj.reduceFlag = 1;
            obj.lastMsg = res.tip;
          }
          if (res.groupId === this.groupId) {
            msgData = {
              msgFlag: 1,
              msg: res.tip,
            };
            this.chatList.push(msgData);
          }
          break;

        // 踢出群聊
        case "reduceData":
          if (res.userIds && res.userIds[0] === store.state.user.userId) {
            this.drawerVisible = false;
            this.reduceFlag = 1;

            if (obj) {
              obj.reduceFlag = 1;
            }
          }
          this.getMemberList();
          if (obj) {
            obj.lastMsg = res.tip;
          }
          if (res.groupId === this.groupId) {
            msgData = {
              msgFlag: 1,
              msg: res.tip,
            };
            this.chatList.push(msgData);
          }
          break;

        // 加入群聊
        case "addData":
          if (obj) {
            obj.lastMsg = res.tip;
            obj.reduceFlag = 0;
          }
          if (res.groupId === this.groupId) {
            this.reduceFlag = 0;
            msgData = {
              msgFlag: 1,
              msg: res.tip,
            };
            this.chatList.push(msgData);
          }

          this.getMemberList();
          break;

        // 修改群名
        case "groupNameData":
          if (res.groupId === this.groupId) {
            this.chatTitle = res.msg;
            msgData = {
              msgFlag: 1,
              msg: res.tip,
            };
            this.chatList.push(msgData);
            this.groupForm.groupName = res.msg;
          }
          if (obj) {
            obj.groupName = res.msg;
            obj.lastMsg = res.tip;
          }
          break;

        // 消息发送异常
        case "exceptionData":
          break;
        //客服上线通知
        case "onlineData":
          if (this.groupId) {
            if (res.groupId) {
              this.groupId = res.groupId;
              this.chatList.push({
                delFlag: 1,
                msgFlag: 1,
                msg: res.msg,
                sendTime: parseTime(
                  new Date(res.sendTime),
                  "{y}-{m}-{d} {h}:{i}:{s}"
                ),
                sendUserName: res.sendUserName,
                sendUserId: res.sendUserId,
                show: false,
              });
            }
          }
          break;

        default:
          break;
      }
      this.$nextTick(() => {
        this.scrollBottom(this.groupId);
      });
    },
    // 时间转换
    timeStampToTime(time) {
      var date = time;
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? "0" + minute : minute;
      var s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + s;
    },
    websocketclose(e) {
      // console.log("websocket关闭")
      // code 1000 是主动关闭
      if (e.code !== 1000) {
        this.webSocketInit();
      }
    },
    // 主动关闭
    close() {
      this.ws.close(1000);
    },
    // 连接成功
    websocketOpen(e) {
      console.log("连接成功");
    },
    //数据发送
    websocketsend(agentData, callback) {
      console.log("发送数据=", agentData);
      this.$nextTick(() => {
        this.scrollBottom(this.groupId);
      });
      if (this.ws.readyState === WebSocket.OPEN) {
        //若是ws开启状态
        this.ws.send(JSON.stringify(agentData));
        // 获取游客信息
        if (this.nowUserId == "" || this.nowUserId == null) {
          this.getTouristInfo();
        }
        // this.getChatHistoryPage();
      } else {
        this.$message.warning("发送失败");
      }
    },
    // 回车发送
    enterSendBtn(event) {
      if (event.shiftKey && event.keyCode === 13) {
      } else if (event.keyCode === 13) {
        event.preventDefault();
        this.sendBtn();
      }
    },
    // 发送按钮
    sendBtn() {
      const message = this.sendMessage.replace(/\n/g, "").replace(/ /g, "");
      if (!message) {
        return;
      } else if (!this.artificialOrNot) {
        // 自动回复渠道
        this.cardBtn(message, 2);
      } else {
        // 人工通讯渠道
        this.addSessionList();
      }
    },
    // 点击问题卡片列表
    cardBtn(data, type) {
      // 获取游客用户信息
      if (!this.nowUserId) {
        this.getTouristInfo();
      }
      let message = null;
      if (type == 1) {
        message = data.problem.replace(/\n/g, "").replace(/ /g, "");
      } else {
        message = data.replace(/\n/g, "").replace(/ /g, "");
        this.filterForm.problem = message;
      }
      this.chatList.push({
        delFlag: 0,
        unreadFlag: "已读",
        msgFlag: 0,
        msg: message,
        sendTime: parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
        sendUserName: "游客",
        sendUserId: this.nowUserId,
        show: false,
      });
      this.getProblemAnswer(data, type);
    },
    // 根据data获取问题预设答案信息
    async getProblemAnswer(data, type) {
      try {
        //判断是点击卡片还是消息
        let message = null;
        if (type == 1) {
          message = data.answer;
        } else {
          // 接口获取回复答案
          if (!this.classifyCode) {
            this.$message.error("分类编码不能为空！");
            return;
          }
          this.loading = true;
          this.filterForm.classifyCode = this.classifyCode;
          let response = await getPage(this.filterForm);
          console.log("答案=", response);
          if (response.code == "00000") {
            // 判断是否有返回值
            if (response.data.rows.length > 0) {
              // 有-直接把答案赋值
              message = response.data.rows[0].answer;
            } else {
              // 没有-回复查不到，请转人工
              message = "很抱歉，未能搜索到相关答案，请联系人工客服确认！";
            }
          } else {
            message = "很抱歉，未能搜索到相关答案，请联系人工客服确认！";
          }
          // 重置搜索参数
          this.handleReset();
        }
        this.chatList.push({
          delFlag: 0,
          unreadFlag: "已读",
          msgFlag: 0,
          msg: message,
          sendTime: parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
          sendUserName: "客服",
          sendUserId: "客服",
          show: false,
        });
      } catch (error) {
        this.$message.error("获取结果失败，请联系管理员！");
        this.handleReset();
      } finally {
        // 滑动到聊天底部
        this.$nextTick(() => {
          this.scrollBottom();
        });
      }
    },
    // 接口查询问题预设答案
    getProblemAnswerLine() {
      if (!this.classifyCode) {
        this.$message.error("分类编码不能为空！");
        return;
      }
      this.loading = true;
      getPage({
        ...this.filterForm,
        classifyCode: this.classifyCode,
      })
        .then((res) => {
          console.log("问题预设=", res);
          if (res.code == "00000") {
            this.cardDataList = res.data.rows;
            this.chatList.push({
              card: true,
              delFlag: 0,
              msgFlag: 0,
              msg: this.change(res.data.rows),
              sendTime: parseTime(new Date(), "{y}-{m}-{d} {h}-{i}-{s}"),
              sendUserName: "客服",
              sendUserId: "客服",
              show: false,
            });
            this.loading = false;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 重置参数
    handleReset() {
      this.filterForm = {
        pageNo: 1,
        pageSize: 10,
        problem: "",
      };
      // 清空聊天框信息
      this.sendMessage = "";
    },
    // 左侧对话列表中不存在，即添加
    async addSessionList() {
      // 发送消息前获取用户当前groupId
      const chatList = await getAccessInfoApi({touristUuid:this.youkeId});
      // console.log("聊天信息-chatList**",chatList)
      if (chatList.data.length > 0) {
        let dataChat = chatList.data[chatList.data.length - 1];
        // 判断最后一条数据接收人是否为空，不为空--根据信息获取最新groupId
        if (dataChat.accessUserId != null && dataChat.accessUserId != "") {
          // console.log("11111111**,获取组Id")
          const { code, data } = await chatGroupQueryVisitorApi({
            userId: dataChat.accessUserId,
            touristId: dataChat.sendUserId,
          });
          // console.log("组Id-data**",data)
          if (code === "00000") {
            this.groupId = data.groupId;
            this.nowChat = true;
            this.fixedFlag = data.fixedFlag;
          }
        }
      }
      let sendData = {
        delFlag: 0,
        msgFlag: 0,
        groupId: this.groupId,
        msg: this.sendMessage.replace(/</g, "&lt;"),
        code: "msgData",
        fixedFlag: this.fixedFlag,
        sendUserName: "",
        sendUserId: this.nowUserId,
      };
      this.websocketsend(sendData);
    },
    // 使会话滚动到最底部
    scrollBottom() {
      this.$refs.lastChatItemRef.scrollIntoView();
    },
    // 选择对话
    selectSession(item, index) {
      if (item.unreadData > 0) {
        let sendData = {
          groupId: item.groupId,
          code: "readData",
        };
        this.websocketsend(sendData);
      }

      this.sessionActive = item.groupId;
      this.chatTitle = item.groupName;
      this.groupId = item.groupId;
      this.fixedFlag = item.fixedFlag;
      this.sessionList[item.groupId].unreadData = 0;
      this.moreMessageBtnShow = true;
      this.groupInfo = item;
      this.reduceFlag = item.reduceFlag;
      this.getChatHistoryList();

      if (item.fixedFlag === 1 && item.reduceFlag === 0) {
        this.groupForm.groupName = item.groupName;
        this.getMemberList();
      }
    },
    // 前台获取uuid
    getTouristUid() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "2";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";
      var uuid = s.join("");
      return uuid
    },
    // 转接人工
    switchServisePerson() {
      if (this.nowUserId == "" || this.nowUserId == null) {
        this.getTouristInfo();
      }
      let lastRequestTime = this.lastRequestTime;
      // 获取当前时间
      const currentTime = new Date().getTime();
      if (lastRequestTime && currentTime - lastRequestTime < 180 * 1000) {
        this.$message.warning("操作过于频繁，请稍后再试！");
      } else {
        this.lastRequestTime = currentTime;
        this.$confirm("确定转接人工?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then((res) => {
            // 判断Id是否为空，是-获取用户信息
            if (this.nowUserId == "" || this.nowUserId == null) {
              this.getTouristInfo();
            }
            let dataarry = this.chatList.filter(
              (item) => item.sendUserName == "游客"
            );
            if (dataarry.length > 0) {
              return transferToArtificalList({chatAccessInfoPojoList:dataarry,touristUuid:this.youkeId});
            } else {
              return { code: "00000" };
            }
          })
          .then((res) => {
            if (res.code == "00000") {
              this.$message.success("操作成功，请耐心等待客服接入！");
              this.artificialOrNot = true;
              // 重新建立链接
              // this.webSocketInit();
              // 接口获取聊天数据
              this.getChatHistoryPage();
            }
          })
          .catch((err) => {
            this.$message.error("取消操作！");
            this.lastRequestTime = null;
          });
      }
    },
    // 查询聊天记录
    getChatHistoryPage() {
      /** 查询客服信息接入列表 */
      this.loading = true;
      // 判断是否人工聊天窗口-
      if (this.artificialOrNot) {
        // 是--获取以往聊天记录回显
        getAccessInfoApi({touristUuid:this.youkeId}).then((response) => {
          this.chatList = [];
          // console.log("response=",response)
          if (response.code == "00000") {
            if (response.data.length < 10) {
              this.moreMessageBtnShow = false;
            }
            let dataChat = response.data[response.data.length - 1];
            //判断最新一条数据是否有接收人，
            if (dataChat.accessUserId != null && dataChat.accessUserId != "") {
              // console.log("11111111111111111111")
              //有--拿sendId与accessUser(接收人id)获取groupId
              chatGroupQueryVisitorApi({
                userId: dataChat.accessUserId,
                touristId: dataChat.sendUserId,
              }).then(({ code, data }) => {
                if (code === "00000") {
                  this.groupId = data.groupId;
                  this.nowChat = true;
                  this.fixedFlag = data.fixedFlag;
                  this.getChatHistoryList();
                }
              });
            } else {
              response.data.forEach((element) => {
                this.chatList.push({
                  infoId: element.infoId,
                  delFlag: 0,
                  msgFlag: 0,
                  msg: element.msg,
                  sendTime: element.sendTime,
                  sendUserName: element.sendUserName,
                  sendUserId: element.sendUserId,
                  show: false,
                });
              });
              // 滑动到聊天底部
              this.$nextTick(() => {
                this.scrollBottom();
              });
            }
          }
          this.loading = false;
        });
      } else {
        // 否--获取问题列表卡片
        this.getProblemCardList();
      }
    },
    // 获取问题列表卡片
    getProblemCardList() {
      /** 查询问题卡片 */
      if (!this.classifyCode) {
        return;
      }
      this.loading = true;
      getPage({
        ...this.filterForm,
        classifyCode: this.classifyCode,
      })
        .then((res) => {
          if (res.code == "00000") {
            this.cardDataList = res.data.rows;
            this.chatList.push({
              card: true,
              delFlag: 0,
              msgFlag: 0,
              msg: this.change(res.data.rows),
              sendTime: parseTime(new Date(), "{y}-{m}-{d} {h}-{i}-{s}"),
              sendUserName: "客服",
              sendUserId: "客服",
              show: false,
            });
            this.loading = false;
            // 滑动到聊天底部
            this.$nextTick(() => {
              this.scrollBottom();
            });
          }
        })
        .catch(() => {
          this.loading = false;
        });
      // const dataList = [
      //   {
      //     wtms:"申请退款操作步骤1？"
      //   },
      //   {
      //     wtms:"申请退款操作步骤2？"
      //   },
      //   {
      //     wtms:"申请退款操作步骤3？"
      //   },
      //   {
      //     wtms:"申请退款操作步骤4？"
      //   },
      //   {
      //     wtms:"申请退款操作步骤5？"
      //   },
      //   {
      //     wtms:"申请退款操作步骤6？"
      //   },
      //   {
      //     wtms:"申请退款操作步骤7？"
      //   },
      //   {
      //     wtms:"申请退款操作步骤8？"
      //   },
      //   {
      //     wtms:"申请退款操作步骤9？"
      //   },
      //   {
      //     wtms:"申请退款操作步骤10？"
      //   },
      //   {
      //     wtms:"申请退款操作步骤11？"
      //   },
      // ]
      // this.cardDataList = dataList
      // this.chatList.push({
      //   card:true,
      //   delFlag: 0,
      //   msgFlag: 0,
      //   msg: this.change(dataList),
      //   sendTime: parseTime(new Date(), '{y}-{m}-{d} {h}-{i}-{s}'),
      //   sendUserName: "客服",
      //   sendUserId: "客服",
      //   show: false
      // })
    },
    // 获取应用问题多级列表
    async getTreeOptions() {
      let msgTree = [];
      // 判断缓存有没有数据
      if (localStorage.getItem("treeArr")) {
        msgTree = JSON.parse(localStorage.getItem("treeArr"));
        let nullAryy = false;
        msgTree.forEach((element) => {
          if (localStorage.getItem(element.value)) {
            element.children = JSON.parse(localStorage.getItem(element.value));
            nullAryy = true;
          }
        });
        if (!nullAryy) {
          msgTree = await this.getTreeCascader();
          // 获取到数据放到缓存
          localStorage.setItem("treeArr", JSON.stringify(msgTree));
        }
      } else {
        msgTree = await this.getTreeCascader();
        // 获取到数据放到缓存
        localStorage.setItem("treeArr", JSON.stringify(msgTree));
      }
      this.chatList.push({
        cascader: true,
        delFlag: 0,
        msgFlag: 0,
        msg: msgTree,
        sendTime: parseTime(new Date(), "{y}-{m}-{d} {h}-{i}-{s}"),
        sendUserName: "客服",
        sendUserId: "客服",
        show: false,
      });
    },
    async getTreeCascader() {
      let res = await getSystemInfoList();
      let treeArr = res.data.map((item) => {
        return {
          label: item.systemName,
          value: item.systemId,
          children: [],
        };
      });
      treeArr.forEach(async (element) => {
        let children = await getProblemType(element.value);
        if (children.data.rows.length >= 0) {
          let newChildren = children.data.rows.map((item) => {
            return {
              label: item.classifyName,
              value: item.classifyCode,
              ...item,
            };
          });
          element.children = newChildren;
          localStorage.setItem(element.value, JSON.stringify(newChildren));
        }
      });
      return treeArr;
    },
    // 监听级联选择器值的变化
    changeCascader(data) {
      if (data != null && data != "" && data != undefined) {
        this.classifyCode = data;
        this.getProblemCardList();
      }
    },
    // 换一换
    changeData(index) {
      this.chatList[index].msg = this.change(this.cardDataList);
    },
    change(dataList) {
      let arrayShow = [];
      let index = 0;
      if (this.index === dataList.length) {
        this.index = 0;
      }
      for (let i = this.index; i < this.index + 5; i++) {
        if (dataList[i]) {
          arrayShow.push(dataList[i]);
          index = i;
        }
      }
      this.index = index + 1;
      return arrayShow;
    },
    // 查询人员对话种的聊天记录
    getChatHistoryList() {
      chatHistoryListVisitorApi({
        groupId: this.groupId,
        touristUuid: this.youkeId
      }).then(({ data, code }) => {
        console.log("chatHistoryListVisitorApi=", data);
        if (code === "00000") {
          this.chatList = data.map((item) => ({ ...item, show: false }));
          if (data.length < 10) {
            this.moreMessageBtnShow = false;
          }
          // 滑动到聊天底部
          this.$nextTick(() => {
            this.scrollBottom();
          });
        }
      });
    },
    // 鼠标右键
    rightMouse(item, event) {
      item.mouseRightShow = true;
      item.rightContainerTop = event.layerY + 5 + "px";
      item.rightContainerLeft = event.layerX + 5 + "px";
      this.choseId = item.groupId;
      this.delButton = true;
    },
    //关闭删除按钮
    closeDelButton() {
      this.delButton = false;
      this.choseId = "";
    },
    // 删除对话
    delSession(item, index) {
      if (item.groupId === this.groupId) {
        this.groupId = "";
        this.chatTitle = "";
        this.chatList = [];
      }
      delete this.sessionList[item.groupId];
      chatHistoryDelApi({
        groupId: item.groupId,
      });
    },
    // 查看更多消息
    getMoreMessage() {
      getAccessInfoApi({touristUuid:this.youkeId}).then(({ data, code }) => {
        if (code === "00000") {
          if (data.length < 10) {
            this.moreMessageBtnShow = false;
          }
          this.chatList = [
            ...data.map((item) => ({ ...item, show: false })),
            ...this.chatList,
          ];
          this.$nextTick(() => {
            const infoId = this.chatList[data.length - 1].infoId;
            document.getElementById("infoId-" + infoId).scrollIntoView();
          });
        }
      });
    },
    // 发送表情
    sendEmoji(val) {
      console.log("标签=", val);
      this.sendMessage += val;
    },
    // 上传成功回调
    handleAvatarSuccess({ data }) {
      let sendData = {
        groupId: this.groupId,
        msg: data.fileOriginName,
        fileSuffix: data.fileSuffix,
        fileSizeInfo: data.fileSizeInfo,
        fileId: data.fileId,
        code: "msgData",
        sendUserName: store.state.user.name,
        sendUserId: store.state.user.userId,
      };
      this.websocketsend(sendData);

      let obj = this.sessionList[this.groupId];
      if (obj) {
        obj.lastMsg = data.fileOriginName;
        obj.lastTime = parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}");
      } else {
        this.sessionList[this.groupId] = {
          unreadData: 0,
          lastMsg: data.fileOriginName,
          groupId: this.groupId,
          groupName: this.userInfoInPage.realName,
          lastTime: parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
        };
        this.sessionActive = this.groupId;
      }
    },
    // 上传之前回调
    beforeAvatarUpload(rawFile) {
      if (rawFile.size / 1024 / 1024 > 10) {
        this.$message.error("文件大小不可超过10M!");
        return false;
      }
      return true;
    },
    // 获取图片
    getIcon(item) {
      return (
        this.baseURL() + `/sysFileInfo/public/preview?fileId=${item.fileId}`
      );
    },
    // 下载按钮
    downloadBtn(item) {
      // window.location.href = this.baseURL()+`sysFileInfo/publicDownload?fileId=${item.fileId}`
      // 本地
      window.location.href = `http://localhost:9528/dev-api/file/sysFileInfo/publicDownload?fileId=${item.fileId}`;
    },
    // 撤回按钮
    revokeBtn(item, index) {
      console.log("item=", item);
      revokeAccessInfoApi({ id: item.infoId }).then(() => {
        this.getChatHistoryPage();
      });
    },
    // 撤回按钮
    revokeBtnShowFn(item, index) {
      const time = new Date().getTime() - new Date(item.sendTime).getTime();
      if (time < 1000 * 60 * 2) {
        item.show = true;
      }
    },
    // 群组设置按钮 / 查询群组信息
    setGroupBtn() {
      this.drawerVisible = true;
    },
    // 设置群组名称
    groupNameBlur() {
      if (!this.groupForm.groupName) {
        this.groupForm.groupName = this.groupInfo.groupName;
        return this.$message({
          type: "warning",
          message: "群组名称不能为空",
        });
      }
      chatGroupEditApi({
        groupId: this.groupId,
        groupName: this.groupForm.groupName,
      }).then(({ code, data }) => {
        if (code === "00000") {
          this.chatTitle = this.groupForm.groupName;
          const obj = this.sessionList[this.groupId];
          obj.groupName = this.groupForm.groupName;
        }
      });
    },
    // 解散群组按钮
    dissolveGroupBtn() {
      this.$confirm("确定删除群组?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        chatGroupDelApi({
          groupId: this.groupId,
        }).then(({ code, data }) => {
          if (code === "00000") {
            const obj = this.sessionList[this.groupId];
            obj.reduceFlag = 1;
            this.reduceFlag = 1;
            this.drawerVisible = false;
            this.$message({ type: "success", message: "操作成功" });
          }
        });
      });
    },
    // 退出群组按钮
    exitGroupBtn() {
      this.$confirm("确定退出群组?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        chatGroupExitApi({
          groupId: this.groupId,
        }).then(({ code, data }) => {
          if (code === "00000") {
            this.reduceFlag = 1;
            this.drawerVisible = false;
            const obj = this.sessionList[this.groupId];
            if (obj) {
              obj.reduceFlag = 1;
            }
            this.$message({ type: "success", message: "操作成功" });
          }
        });
      });
    },
    // 获取成员
    getMemberList() {
      chatGroupInfoApi({
        groupId: this.groupId,
      }).then(({ code, data }) => {
        if (code === "00000") {
          this.groupUsers = data.groupUsers;
          this.adminFlag = data.createUserId === store.state.user.userId;
        }
      });
    },
    // 添加成员
    addMember() {
      this.addMemberGroupId = this.groupId;
      this.addBtn();
    },
    // 关闭群聊设置弹窗
    closeDialogQl() {
      // 重置addMemberGroupId为空
      this.addMemberGroupId = "";
    },
    // 删除按钮显示
    delTrue(item) {
      this.delUserId = item.userId;
    },
    // 删除按钮隐藏
    delFalse() {
      this.delUserId = "";
    },
    //删除按钮判断
    showAvatar(item) {
      return (
        this.adminFlag &&
        item.userId !== this.nowUserId &&
        this.delUserId == item.userId
      );
    },
    // 删除成员
    delMember(item, index) {
      this.$confirm("确定删除该成员?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        chatGroupMemberApi({
          addOrReduce: 0,
          groupId: this.groupId,
          groupUserIds: [item.userId],
        }).then(({ code, data }) => {
          if (code === "00000") {
            this.groupUsers.splice(index, 1);
            this.$message({
              type: "success",
              message: "操作成功",
            });
          }
        });
      });
    },
    //--弹窗字段信息--------
    filterNode(value, data) {
      if (!value) {
        return true;
      }
      return data.orgName.indexOf(value) !== -1;
    },
    // 人员树选择
    checkUserList(node, data) {
      this.selectedUserList = data.checkedNodes;
      if (data.checkedNodes.length == 2) {
        let arry = [];
        arry.push(node);
        //单选实现
        this.$refs.treeRef.setCheckedKeys([node.orgId]);
        this.selectedUserList = arry;
      }
    },
    // 创建群聊
    addPeopleBtn() {
      this.groupId = "";
      this.addBtn();
    },
    addBtn() {
      this.dialogVisible = true;
      this.selectedUserList = [];
      // 获取人员树
      // getUserTree().then((res) => {
      //   if (res.code === '00000') {
      //     this.treeData = res.data
      //   }
      // })
      getOrgTreeApi().then(({ code, data }) => {
        if (code === "00000") {
          let treeData = this.getNewOrgUserTree(data);
          console.log("treeData=", treeData);
          this.treeData = treeData;
        }
      });
    },
    // 处理组织树获取新数据
    getNewOrgUserTree(tree) {
      tree.map(async (element) => {
        // console.log("element=",element)
        let newJson = {};
        if (element.orgParentId === "-1") {
          element.disabled = true;
        }
        let orgId = element.orgId;
        if (orgId && element.children) {
          element.children.map((child) => {
            child.disabled = true;
          });
          let userList = await this.getUserList(orgId);
          // console.log("userList=",userList)
          // 过滤当前部门之下的数据
          let newUserList = userList.filter(
            (item) => item.orgName == element.orgName
          );
          // console.log("newUserList=",newUserList)
          // 改变数组内容
          let realUserList = newUserList.map((item2) => ({
            ...item2,
            orgName: item2.realName,
            orgId: item2.userId,
            id: item2.userId,
            name: item2.realName,
          }));
          // console.log("realUserList=",realUserList)
          element.children = realUserList.concat(element.children);
          // console.log("element.children=",element.children)
        }
        if (element.children && element.children.length > 0) {
          this.getNewOrgUserTree(element.children);
        }
      });
      return tree;
    },
    // 设置部门禁止选择
    setDisabled(data) {
      if (data.nodeType === "org" || store.state.user.userId === data.id) {
        return true;
      } else {
        return false;
      }
    },
    // 创建群聊确定
    confirmBtn() {
      var groupName = "";
      var groupUserIds = [];
      this.selectedUserList.forEach((item) => {
        if (store.state.user.userId != item.id) {
          groupName = groupName + item.name + ",";
          groupUserIds.push(item.id);
        }
      });
      if (this.selectedUserList.length >= 2) {
        this.$message.warning("至多转接给一个人");
        return;
      }

      groupName = groupName + store.state.user.name;
      chatGroupAddApi({
        groupName: groupName,
        groupUserIds: groupUserIds,
      }).then(({ code, data }) => {
        if (code === "00000") {
          this.dialogVisible = false;
          this.isChat = true;
          this.newGroupId = data.groupId;
        }
      });
    },
    userHandleClose(tag, index) {
      this.selectedUserList.splice(index, 1);
      this.$refs.treeRef.setChecked(tag.userId, false);
    },
    //----组织显示-------------------------------------
    leftShow(val) {
      if (val == 1) {
        this.isChat = true;
        this.isOrg = false;
      } else {
        this.isChat = false;
        this.isOrg = true;
        this.getOrgTree();
      }
    },
    // 获取部门树
    getOrgTree() {
      // 懒加载
      // getOrgTreeApi({orgId: 0}).then(({ code, data }) => {
      //   if (code === '00000') {
      //     this.orgTree = data
      //     this.selectedOrg = data[0]
      //     this.currentKey = data[0].id
      //     this.$nextTick(() => {
      //       this.$refs.orgTreeRef.setCurrentKey(res.data[0].id)
      //     })
      //   }
      // })
      getOrgTreeApi().then(({ code, data }) => {
        if (code === "00000") {
          this.orgTree = data;
        }
      });
    },
    // // 懒加载
    load(tree, resolve) {
      // console.log("tree=",tree)
      let orgid = "";
      if (!tree.data || tree.data.length == 0) {
        orgid = 0;
        return;
      } else {
        orgid = tree.data.id;
      }
      getOrgTreeApi({ orgId: orgid }).then((res) => {
        // console.log("asdhkja=",res)
        const data = res.data.map((item, index) => {
          this.selectedOrg = res.data[0];
          this.currentKey = res.data[0].id;
          this.$nextTick(() => {
            this.$refs.orgTreeRef.setCurrentKey(res.data[0].id);
          });
          return item;
        });
        resolve(data);
      });
    },
    // 树节点被点击的时候触发
    async nodeClick(data) {
      console.log("asdjhajkdb=", data);
      // 重置数据
      this.userList = [];
      // this.getUserList(data.id)
      let res = await getSysUserPageApi({
        account: "",
        realName: "",
        pageNo: 1,
        pageSize: 100,
        orgId: data.orgId,
        containSelf: false,
      });
      // console.log("resujh=",res)
      this.userList = res.data.rows;
      this.totalRows = res.data.totalRows;

      this.orgName = data.orgName;
      this.userActive = "";
      this.userInfo = {};
    },
    // 获取当前组织下的人员
    async getUserList(orgId) {
      let res = await getSysUserPageApi({
        account: "",
        realName: "",
        pageNo: 1,
        pageSize: 100,
        orgId: orgId,
        containSelf: false,
      });
      if (res.code === "00000") {
        return res.data.rows;
      }
    },
    //查看用户详情
    userClick(item, index) {
      this.userActive = index;
      this.userInfo = item;
    },
    //发送信息
    sendMessageToUser(userInfo) {
      console.log("userInfo=", userInfo);
      chatGroupQueryApi({
        userId: userInfo.userId,
      }).then(({ code, data }) => {
        console.log("data=", data);
        if (code === "00000") {
          this.leftShow(1);
          this.chatTitle = userInfo.realName;
          this.groupId = data.groupId;
          this.nowChat = true;
          this.fixedFlag = data.fixedFlag;
          this.getChatHistoryList();
        }
      });
    },
  },
  mounted() {
    // 判断当前
    // this.getChatHistoryPage();
  },

  destroyed() {
    this.close();
  },
  watch: {
    filterText(val) {
      this.$refs.treeRef.filter(val);
    },
    orgFilterText(val) {
      this.$refs.orgTreeRef.filter(val);
    },
    userInfo(val) {
      // console.log("val=",val);
      this.userInfoInPage = val;
      this.chatTitle = val.realName;
    },
    newGroupId() {
      this.getChatHistoryPage();
    },
  },
};
</script>


<style lang="scss" scoped>
p {
  margin: 0;
}
div.chat {
  display: flex;
  height: 80vh;
  width: 100%;
}
// 右侧对话列表
.chat-container {
  flex: 1;
  height: 100%;
  width: 70%;
  // min-height: 85vh;
  
  .chat-list {
    height: calc(75% - 1px);

    border-bottom: 1px solid #ddd;

    .chat-title {
      height: 7vh;
      padding: 10px;
      font-size: 18px;
      font-style: italic;
      background: #fff;
      border-bottom: 1px solid #ddd;
      align-items: center;
      display: flex;
    }
    ul {
      margin: 0px;
      padding: 10px 8px;
      height: 89%;
      overflow-y: auto;
      background: #f2f5f7;
      .more-message-btn {
        padding-top: 5px;
        text-align: center;
        .el-button {
          font-size: 12px;
          font-style: italic;
        }
      }
      li {
        padding-left: 10px;
        padding-right: 10px;
        list-style-type: none;
      }
      // 我自己的样式
      .myself {
        display: flex;
        justify-content: right;
        & > div:first-child {
          text-align: right;
          padding-right: 10px;
          & > p:first-child {
            font-size: 14px;
            span {
              font-size: 12px;
            }
          }
          p.read-or-not {
            text-align: left;
            margin-top: 5px;
            color: #b0b2b1;
            font-size: 13px;
          }

          & > div {
            display: inline-block;
            position: relative;
          }
          .withdraw-wrapper {
            position: absolute;
            background: #1d2b3f;
            padding: 6px 15px;
            border-radius: 3px;
            left: 50%;
            top: -20px;
            transform: translateX(-50%);
            &::after {
              content: "";
              position: absolute;
              left: 25px;
              bottom: -10px;
              border: 5px solid transparent;
              border-top-color: #1d2b3f;
            }
          }
        }

        & > div:last-child {
          span {
            display: inline-block;
            width: 40px;
            text-align: center;
            line-height: 40px;
            font-size: 20px;
            color: #fff;
            background: #75b9e6;
            border-radius: 50%;
          }
        }
      }

      // 对方的样式
      .others {
        display: flex;
        justify-content: left;

        & > div:first-child {
          span {
            display: inline-block;
            width: 40px;
            text-align: center;
            line-height: 40px;
            font-size: 20px;
            color: #fff;
            background: #5ac994;
            border-radius: 50%;
          }
        }
        & > div:last-child {
          padding-left: 8px;
          p:first-child {
            text-align: left;
            font-size: 14px;

            span {
              font-size: 12px;
            }
          }
        }

        .msg-wrapper {
          background: #ffffff !important;
        }
      }

      // 文件
      .file-wrapper {
        margin-top: 10px;
        ::v-deep .img-file {
          img {
            max-width: 300px;
            max-height: 300px;
            cursor: pointer;
          }
        }
        .text {
          font-size: 14px;
        }

        .item {
          margin-bottom: 18px;
        }

        .clearfix:before,
        .clearfix:after {
          display: table;
          content: "";
        }
        .clearfix:after {
          clear: both;
        }

        .box-card {
          width: 380px;
        }
      }

      // 文本信息
      .msg-wrapper {
        margin-top: 8px;
        background: #def4ff;
        padding: 5px 10px;
        width: fit-content;
        max-width: 500px;
        border-radius: 5px;
        font-size: 15px;
        border-top-right-radius: 0px;
        white-space: pre-wrap;
        text-align: left;
      }
    }
  }

  // 消息发送框
  .chat-send {
    height: 23%;
    background: #fff;
    position: relative;
    // 工具栏
    .chat-tool {
      border-bottom: 1px solid #ddd;
      height: 5vh;
      .chat-tool-item {
        display: flex;
        margin: auto;
        align-items: center;
        height: 100%;
        color: #98A0AA;
        padding-left: 19px;
        .chat-tool-item-upload {
          font-size: 26px;
          margin-left: 10px;
        }
      }
    }

    // 消息输入框
    .chat-input {
        margin-top: -5px;
        padding: 5px 5px;
        ::v-deep.el-textarea {
          .el-textarea__inner {
            border: none;
            box-shadow: 0 0 0 0px;
            background: transparent;
          }
        }
      }

    .chat-send-btn {
      padding: 5px 30px 30px 30px;
      margin-top: 10px;
      text-align: right;
    }
  }
}
.avatar {
  background-color: #5ac994;
  font-size: 20px;
  size: 50px;
}
// 左侧个人信息
.my-info {
  width: 39px;
  padding: 20px 0;
  background: #428dbe;
  text-align: center;
  img {
    width: 30px;
  }
  .not-avatar {
    margin-top: 15px;
    cursor: pointer;
  }
}
.ulSpan {
  display: inline-block;
  width: 80px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
::v-deep .el-cascader-menu {
  height: 151px;
}
</style>
